{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.5/dist-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n",
      "/usr/local/lib/python3.5/dist-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n",
      "  \"This module will be removed in 0.20.\", DeprecationWarning)\n"
     ]
    }
   ],
   "source": [
    "from utils import *\n",
    "import tensorflow as tf\n",
    "from sklearn.cross_validation import train_test_split\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['negative', 'positive']\n",
      "10662\n",
      "10662\n"
     ]
    }
   ],
   "source": [
    "trainset = sklearn.datasets.load_files(container_path = 'data', encoding = 'UTF-8')\n",
    "trainset.data, trainset.target = separate_dataset(trainset,1.0)\n",
    "print (trainset.target_names)\n",
    "print (len(trainset.data))\n",
    "print (len(trainset.target))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "ONEHOT = np.zeros((len(trainset.data),len(trainset.target_names)))\n",
    "ONEHOT[np.arange(len(trainset.data)),trainset.target] = 1.0\n",
    "train_X, test_X, train_Y, test_Y, train_onehot, test_onehot = train_test_split(trainset.data, \n",
    "                                                                               trainset.target, \n",
    "                                                                               ONEHOT, test_size = 0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "vocab from size: 20465\n",
      "Most common words [('the', 10129), ('a', 7312), ('and', 6199), ('of', 6063), ('to', 4233), ('is', 3378)]\n",
      "Sample data [4, 645, 9, 2686, 8, 22, 4, 3418, 18083, 98] ['the', 'rock', 'is', 'destined', 'to', 'be', 'the', '21st', 'centurys', 'new']\n"
     ]
    }
   ],
   "source": [
    "concat = ' '.join(trainset.data).split()\n",
    "vocabulary_size = len(list(set(concat)))\n",
    "data, count, dictionary, rev_dictionary = build_dataset(concat, vocabulary_size)\n",
    "print('vocab from size: %d'%(vocabulary_size))\n",
    "print('Most common words', count[4:10])\n",
    "print('Sample data', data[:10], [rev_dictionary[i] for i in data[:10]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "GO = dictionary['GO']\n",
    "PAD = dictionary['PAD']\n",
    "EOS = dictionary['EOS']\n",
    "UNK = dictionary['UNK']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Model:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size,\n",
    "                 dict_size, dimension_output, learning_rate):\n",
    "        \n",
    "        def cells(size, reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size,reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.float32, [None, dimension_output])\n",
    "        encoder_embeddings = tf.Variable(tf.random_uniform([dict_size, embedded_size], -1, 1))\n",
    "        encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layer // 2),\n",
    "                cell_bw = cells(size_layer // 2),\n",
    "                inputs = encoder_embedded,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            encoder_embedded = tf.concat((out_fw, out_bw), 2)\n",
    "        W = tf.get_variable('w',shape=(size_layer, dimension_output),initializer=tf.orthogonal_initializer())\n",
    "        b = tf.get_variable('b',shape=(dimension_output),initializer=tf.zeros_initializer())\n",
    "        self.logits = tf.matmul(encoder_embedded[:, -1], W) + b\n",
    "        self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = self.logits, labels = self.Y))\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        correct_pred = tf.equal(tf.argmax(self.logits, 1), tf.argmax(self.Y, 1))\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 128\n",
    "num_layers = 1\n",
    "embedded_size = 128\n",
    "dimension_output = len(trainset.target_names)\n",
    "learning_rate = 1e-3\n",
    "maxlen = 50\n",
    "batch_size = 128"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Model(size_layer,num_layers,embedded_size,vocabulary_size+4,dimension_output,learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 0, pass acc: 0.000000, current acc: 0.612305\n",
      "time taken: 6.498684406280518\n",
      "epoch: 0, training loss: 0.680209, training acc: 0.556700, valid loss: 0.656689, valid acc: 0.612305\n",
      "\n",
      "epoch: 1, pass acc: 0.612305, current acc: 0.687012\n",
      "time taken: 6.268661260604858\n",
      "epoch: 1, training loss: 0.585188, training acc: 0.691998, valid loss: 0.589634, valid acc: 0.687012\n",
      "\n",
      "epoch: 2, pass acc: 0.687012, current acc: 0.704590\n",
      "time taken: 7.267428159713745\n",
      "epoch: 2, training loss: 0.443354, training acc: 0.799716, valid loss: 0.593762, valid acc: 0.704590\n",
      "\n",
      "epoch: 3, pass acc: 0.704590, current acc: 0.714844\n",
      "time taken: 6.888561487197876\n",
      "epoch: 3, training loss: 0.299202, training acc: 0.878078, valid loss: 0.649373, valid acc: 0.714844\n",
      "\n",
      "epoch: 4, pass acc: 0.714844, current acc: 0.730469\n",
      "time taken: 5.747843027114868\n",
      "epoch: 4, training loss: 0.183097, training acc: 0.931463, valid loss: 0.727147, valid acc: 0.730469\n",
      "\n",
      "time taken: 5.826803684234619\n",
      "epoch: 5, training loss: 0.119946, training acc: 0.955966, valid loss: 1.003781, valid acc: 0.716797\n",
      "\n",
      "epoch: 6, pass acc: 0.730469, current acc: 0.732910\n",
      "time taken: 5.794602155685425\n",
      "epoch: 6, training loss: 0.074948, training acc: 0.975024, valid loss: 0.964103, valid acc: 0.732910\n",
      "\n",
      "time taken: 5.71683144569397\n",
      "epoch: 7, training loss: 0.029955, training acc: 0.993016, valid loss: 1.186900, valid acc: 0.728027\n",
      "\n",
      "epoch: 8, pass acc: 0.732910, current acc: 0.733887\n",
      "time taken: 5.808787822723389\n",
      "epoch: 8, training loss: 0.015328, training acc: 0.997396, valid loss: 1.289874, valid acc: 0.733887\n",
      "\n",
      "epoch: 9, pass acc: 0.733887, current acc: 0.736816\n",
      "time taken: 5.743382692337036\n",
      "epoch: 9, training loss: 0.012468, training acc: 0.998224, valid loss: 1.502274, valid acc: 0.736816\n",
      "\n",
      "time taken: 5.738295793533325\n",
      "epoch: 10, training loss: 0.007309, training acc: 0.999527, valid loss: 1.360602, valid acc: 0.732422\n",
      "\n",
      "time taken: 5.7815351486206055\n",
      "epoch: 11, training loss: 0.004786, training acc: 0.999763, valid loss: 1.420953, valid acc: 0.725586\n",
      "\n",
      "time taken: 5.662769317626953\n",
      "epoch: 12, training loss: 0.004104, training acc: 0.999527, valid loss: 1.677028, valid acc: 0.728027\n",
      "\n",
      "epoch: 13, pass acc: 0.736816, current acc: 0.740723\n",
      "time taken: 5.744422435760498\n",
      "epoch: 13, training loss: 0.002337, training acc: 0.999882, valid loss: 1.515315, valid acc: 0.740723\n",
      "\n",
      "time taken: 5.794926404953003\n",
      "epoch: 14, training loss: 0.001205, training acc: 1.000000, valid loss: 1.538295, valid acc: 0.735352\n",
      "\n",
      "time taken: 5.681676387786865\n",
      "epoch: 15, training loss: 0.000838, training acc: 1.000000, valid loss: 1.638272, valid acc: 0.736816\n",
      "\n",
      "time taken: 5.670816421508789\n",
      "epoch: 16, training loss: 0.000633, training acc: 1.000000, valid loss: 1.706160, valid acc: 0.737305\n",
      "\n",
      "time taken: 4.649846315383911\n",
      "epoch: 17, training loss: 0.000510, training acc: 1.000000, valid loss: 1.754736, valid acc: 0.735352\n",
      "\n",
      "time taken: 2.9159023761749268\n",
      "epoch: 18, training loss: 0.000420, training acc: 1.000000, valid loss: 1.799152, valid acc: 0.733887\n",
      "\n",
      "break epoch:19\n",
      "\n"
     ]
    }
   ],
   "source": [
    "EARLY_STOPPING, CURRENT_CHECKPOINT, CURRENT_ACC, EPOCH = 5, 0, 0, 0\n",
    "while True:\n",
    "    lasttime = time.time()\n",
    "    if CURRENT_CHECKPOINT == EARLY_STOPPING:\n",
    "        print('break epoch:%d\\n'%(EPOCH))\n",
    "        break\n",
    "        \n",
    "    train_acc, train_loss, test_acc, test_loss = 0, 0, 0, 0\n",
    "    for i in range(0, (len(train_X) // batch_size) * batch_size, batch_size):\n",
    "        batch_x = str_idx(train_X[i:i+batch_size],dictionary,maxlen)\n",
    "        acc, loss, _ = sess.run([model.accuracy, model.cost, model.optimizer], \n",
    "                           feed_dict = {model.X : batch_x, model.Y : train_onehot[i:i+batch_size]})\n",
    "        train_loss += loss\n",
    "        train_acc += acc\n",
    "    \n",
    "    for i in range(0, (len(test_X) // batch_size) * batch_size, batch_size):\n",
    "        batch_x = str_idx(test_X[i:i+batch_size],dictionary,maxlen)\n",
    "        acc, loss = sess.run([model.accuracy, model.cost], \n",
    "                           feed_dict = {model.X : batch_x, model.Y : test_onehot[i:i+batch_size]})\n",
    "        test_loss += loss\n",
    "        test_acc += acc\n",
    "    \n",
    "    train_loss /= (len(train_X) // batch_size)\n",
    "    train_acc /= (len(train_X) // batch_size)\n",
    "    test_loss /= (len(test_X) // batch_size)\n",
    "    test_acc /= (len(test_X) // batch_size)\n",
    "    \n",
    "    if test_acc > CURRENT_ACC:\n",
    "        print('epoch: %d, pass acc: %f, current acc: %f'%(EPOCH,CURRENT_ACC, test_acc))\n",
    "        CURRENT_ACC = test_acc\n",
    "        CURRENT_CHECKPOINT = 0\n",
    "    else:\n",
    "        CURRENT_CHECKPOINT += 1\n",
    "        \n",
    "    print('time taken:', time.time()-lasttime)\n",
    "    print('epoch: %d, training loss: %f, training acc: %f, valid loss: %f, valid acc: %f\\n'%(EPOCH,train_loss,\n",
    "                                                                                          train_acc,test_loss,\n",
    "                                                                                          test_acc))\n",
    "    EPOCH += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "             precision    recall  f1-score   support\n",
      "\n",
      "   negative       0.74      0.71      0.73      1078\n",
      "   positive       0.72      0.75      0.73      1055\n",
      "\n",
      "avg / total       0.73      0.73      0.73      2133\n",
      "\n"
     ]
    }
   ],
   "source": [
    "logits = sess.run(model.logits, feed_dict={model.X:str_idx(test_X,dictionary,maxlen)})\n",
    "print(metrics.classification_report(test_Y, np.argmax(logits,1), target_names = trainset.target_names))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
